import { leaveNew, leavePreview } from "../../../utils/request/api";
import User from "../../../utils/user";
import msg from "../../../utils/msg";
import { formatTime } from "../../../utils/util";
import { getInterfaceRoute } from "../../../utils/request/route";
// pages/user/leave/leave.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    leave:{}  as {sr_name:string,sr_id:string},//储存请假的签到名与对应id
    start: false,
    end: false,
    start_time: false,
    end_time: false,
    info: {
      start: '' as string,
      start_time: '第1节' as string,
      end: '' as string,
      end_time: '第11节' as string,
      reason: '' as string,
    },
    currentDate: new Date().getTime(),//时间戳
    start_picker: ['第1节', '第2节', '第3节', '第4节', '第5节', '第6节', '第7节', '第8节', '第9节', '第10节'],
    end_picker: ['第2节', '第3节', '第4节', '第5节', '第6节', '第7节', '第8节', '第9节', '第10节', '第11节'],
    previewData: [] as string[],
    result: [] as string[],//选择请假的课程名称
    sr_leave:[] as {sr_name:string,sr_id:number}[],//选择请假的签到信息的id
    showPreview: false as boolean,
    //图片
    fileList: [] as any,
  },
  //上传图片
  afterRead(event: any) {
    const { file } = event.detail;
    const { fileList = [] } = this.data.fileList;
    fileList.push({ ...file, url: file.url });
    this.setData({
      fileList: fileList,
    });
  },
  //
  getCurrentDate() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1);
    const day = String(now.getDate());
    return `${year}/${month}/${day}`;
  },
  checkTime(){
    let info = this.data.info;
    if(!this._compareDates(info.start,info.end)){
      msg.show('开始日期大于结束日期','请注意');
      return false;
    }
    if(info.start==info.end){
      let reg = /[\u4e00-\u9fa5]/g;
      let start_time=info.start_time.replace(reg,'');
      let end_time=info.end_time.replace(reg,'');
      console.log(start_time, end_time);
      if(Number(start_time)>Number(end_time)){
        msg.show('开始日期大于结束日期','请注意');
        return false;
      }
    }
    return true;
  },
  _compareDates(dateStr1: string, dateStr2: string): boolean {
    const date1: Date = new Date(dateStr1);
    const date2: Date = new Date(dateStr2);
    return date1 <= date2;
  },
  
  submit: async function () {
    if (!this.checkInfo()) {
      msg.show('请填写完整信息', ''); return;
    }
    if (this.data.fileList.length == 0) {
      await msg.confirm('未上传凭证', '是否继续提交');
    }
    if (this.data.showPreview) return;
    if(!this.checkTime())return;
    //todo 上传信息，并显示将会请假的课程
    let info = this.data.info;
    let user = new User;
    let reg = /[\u4e00-\u9fa5]/g;
    info.start_time = info.start_time.replace(reg, '');
    info.end_time = info.end_time.replace(reg, '');
    msg.Loading('上传中');
    await leavePreview({ start: info.start, start_time: info.start_time, end: info.end, end_time: info.end_time, s_code: user.code })
      .then((res: any) => {
        msg.hideLoading();
        //预览
        let leave = res.data.data;
        let sr_names: string = res.data.data.sr_name;
        let previewData: string[] = sr_names.length > 0 ? sr_names.split(',') : [];
        this.setData({
          showPreview: true,
          previewData: previewData,
          leave:leave,
          result: previewData,
        });
        let leave_name = this.data.leave.sr_name.split(',');
        let leave_id = this.data.leave.sr_id.split(',');
        let sr_leave=[] as {sr_name:string,sr_id:number}[];
        leave_name.forEach((item,index)=>{
          if(item!="") 
          sr_leave.push({sr_name:item,sr_id:Number(leave_id[index])});
        });
        this.setData({
          sr_leave:sr_leave,
        })
      });
    msg.hideLoading();
  },
  cancel() {
    this.setData({
      showPreview: false,
    })
  },
  //确认上传
  confirm: async function () {
    msg.Loading('提交中');
    let info = this.data.info;
    let reg = /[\u4e00-\u9fa5]/g;
    info.start_time = info.start_time.replace(reg, '');
    info.end_time = info.end_time.replace(reg, '');
    let user = new User;
    let sr_leave =JSON.stringify(this.data.sr_leave);
    await leaveNew({ start: info.start, start_time: info.start_time, end: info.end, end_time: info.end_time, s_code: user.code, reason: info.reason,sr_leave:sr_leave })
      .then(async (res: any) => {
        //如果有凭证，上传凭证
        let fileList = this.data.fileList;
        if (fileList.length > 0) {
          let leave_id = res.data.data;
          msg.Loading('上传凭证中');
          wx.uploadFile({
            url: getInterfaceRoute('leavePic'), // 仅为示例，非真实的接口地址
            filePath: fileList[0].url,
            name: 'file',
            formData: { leave_id: leave_id },
            success(res: any) {
              msg.hideLoading();
              console.log('pic_res=', res);
              if (res.data.code == '200') {
                return;
              }
            },
            fail(err) {
              msg.hideLoading();
              msg.show('凭证上传失败', '请稍后再试');
            }
          });

        }

        msg.hideLoading();
        if (res.data.code == '200') {
          await msg.show('上传成功', '请等待审核');
          wx.navigateBack();
        }
        else msg.show('上传失败', '请稍后再试');
      });

  },
  //检查输入完整性
  checkInfo() {
    let info = this.data.info;
    if (!info.start || !info.start_time || !info.end || !info.end_time || !info.reason) {
      return false;
    }
    return true;
  },
  getReason(e: any) {
    let input = e.detail.value;
    this.setData({
      ['info.reason']: input,
    });
  },
  onChangeStart(e: any) {
    this.setData({
      ['info.start_time']: e.detail.value,
    });
  },
  chooseTimeStart2() {
    this.setData({
      start_time: true,
    })
  },
  onChangeEnd(e: any) {
    this.setData({
      ['info.end_time']: e.detail.value,
    });
  },
  chooseTimeEnd2() {
    this.setData({
      end_time: true,
    })
  },
  getStart(e: any) {
    let format_time = formatTime(new Date(e.detail));
    let time = format_time.split(' ');
    this.setData({
      ['info.start']: time[0],
      start: false,
    });
  },
  onClose() {
    this.setData({
      end: false,
      start: false,
      start_time: false,
      end_time: false,
    });
  },
  getEnd(e: any) {
    let format_time = formatTime(new Date(e.detail));
    let time = format_time.split(' ');
    this.setData({
      ['info.end']: time[0],
      end: false,
    });
  },
  chooseTimeStart() {
    this.setData({
      start: true,
    })
  },
  chooseTimeEnd() {
    this.setData({
      end: true,
    })
  },
  //前往请假历史
  goToLeaveHistory() {
    wx.navigateTo({
      url: "/pages/user/leave/leaveHistory/leaveHistory",
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.setData({
      ['info.end']: this.getCurrentDate(),
      ['info.start']: this.getCurrentDate(),
    })
  },
  onClickLeft() {
    wx.navigateBack();
  },
  //复选框
  toggle(event: any) {
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },
  onChange(event: any) {
    this.setData({
      result: event.detail,
    });
    let result = this.data.result;
    let leave:string[] = this.data.leave.sr_name.split(',');
    let leave_id = this.data.leave.sr_id.split(',');
    let sr_leave = [] as {sr_name:string,sr_id:number}[];
    result.forEach((item,index) => {
      leave.forEach((item2,index2)=>{
        if(item==item2){
          sr_leave.push({sr_name:item2,sr_id:Number(leave_id[index2])});
        }
      })
    });
    this.setData({
      sr_leave:sr_leave,
    });
  },
  noop(e: any) {
    //console.log(e);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})